//
//  HomeViewController.m
//  jiyujiaProgram
//
//  Created by 中良 赵 on 15/10/13.
//  Copyright (c) 2015年 中良 赵. All rights reserved.
//

#import "HomeViewController.h"
#import "homeCollectionViewCell.h"
#import "CDRTranslucentSideBar.h"
#import "AdvertisingColumn.h"
#import "Common.h"
#import "YueKeViewController.h"
#import "AroudTeachersViewController.h"
#import "GoodTeacherViewController.h"
#import "JiaoShiPaiMingViewController.h"
#import "HuoDongViewController.h"
#import "JSONHTTPClient.h"
#import "MainViewController.h"
#import "ChatListViewController.h"
#import "TuijianShipinViewController.h"
#import "WeAppHttpManager.h"
#import <MediaPlayer/MediaPlayer.h>
#import "VideoModel.h"

@interface HomeViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
{
    NSString *kcellIdentifier;
    NSString *kheaderIdentifier;
    NSString *kfooterIdentifier;
    AdvertisingColumn *_headerADView;
    NSArray *arr;
}
@property (nonatomic, strong) CDRTranslucentSideBar *SideBar;
@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    kcellIdentifier=@"cell";
    kheaderIdentifier=@"header";
    kfooterIdentifier=@"footer";
    [self.collectionView registerNib:[UINib nibWithNibName:@"homeCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:kcellIdentifier];
    //注册headerView Nib的view需要继承UICollectionReusableView
    //    [self.mycollectionview registerNib:[UINib nibWithNibName:@"SQSupplementaryView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kheaderIdentifier];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kheaderIdentifier];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:kfooterIdentifier];
    self.collectionView.allowsMultipleSelection = YES;//默认为NO,是否可以多选
    
    
    /*
     ***广告栏
     */
    float AD_height = 150;//广告栏高度
    _headerADView = [[AdvertisingColumn alloc]initWithFrame:CGRectMake(0, 0, fDeviceWidth, AD_height)];
    _headerADView.backgroundColor = [UIColor blackColor];
    
    /*
     ***加载的数据
     */
    NSArray *imgArray = [NSArray arrayWithObjects:@"QQ20151209-111.png",@"QQ20151209-111.png",@"QQ20151209-111.png",@"QQ20151209-1.png", nil];
    [_headerADView setArray:imgArray];
    [self.headview addSubview:_headerADView];
//    arr=[NSArray arrayWithObjects:@"QQ20151209-2.png",@"QQ20151209-1.png",@"QQ20151209-2.png",@"QQ20151209-1.png", nil];
//    arr=@{@"",@"",@"",@""};
    UILabel *lbl=(UILabel *)[self.headview viewWithTag:11];
    lbl.layer.cornerRadius=5.f;
    lbl.layer.masksToBounds=YES;
    
    lbl.backgroundColor=[UIColor redColor];
    [self creatThirdHttpRequest];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshNumLabel:) name:@"refreshNumLabel" object:nil];
//    self.numLabel = [[UILabel alloc] initWithFrame:CGRectMake(ECSCREEN_W/4*3 + (ECSCREEN_W/3)/2, 5, 16, 16)];
    self.numLabel.clipsToBounds = YES;
    self.numLabel.layer.cornerRadius = 8;
    self.numLabel.font = [UIFont systemFontOfSize:10.f];
    self.numLabel.textAlignment = NSTextAlignmentCenter;
    self.numLabel.backgroundColor = NAVC_COLOR;
    self.numLabel.textColor = ECCOLOR(255, 255, 255, 1);
//    [_fastEntryView addSubview:self.numLabel];
    
    if (self.tabBarItem.badgeValue) {
        self.numLabel.hidden = NO;
        self.numLabel.text = self.tabBarItem.badgeValue;
    }else{
        self.numLabel.hidden = YES;
    }
}

- (void)refreshNumLabel:(NSNotification *)noti
{
    NSString *num = [noti object];
    if ([num integerValue] > 0) {
        self.numLabel.hidden = NO;
        self.numLabel.text = num;
    }else{
        self.numLabel.hidden = YES;
    }
}

- (void)creatThirdHttpRequest
{
    NSDictionary *param = @{
                            @"CLASSIFICATION":@"e47ae78903c24178903557a55e02d4ef",
                            @"CATEGORY":@"",
                            @"STICK":@"1",
                            @"pageIndex":@"0",
                            @"pageSize":@"4",
                            };
    
    [[HttpManager defaultManager] postRequestToUrl:RequestURL(QUERYVIDEOBY) params:param complete:^(BOOL successed, NSDictionary *result) {
        NSLog(@"result===%@",result);
        if (successed) {
            arr=[VideoModel arrayOfModelsFromDictionaries:[result objectForKey:@"data"]];
            NSLog(@"%@",arr);
            [_collectionView reloadData];
        }
        else{

        }
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/**
 *  scroll Timer
 */
#pragma mark 定时滚动scrollView
-(void)viewDidAppear:(BOOL)animated{//显示窗口
    [super viewDidAppear:animated];
    //    [NSThread sleepForTimeInterval:3.0f];//睡眠，所有操作都不起作用
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [_headerADView openTimer];//开启定时器
    });
}
-(void)viewWillDisappear:(BOOL)animated{//将要隐藏窗口  setModalTransitionStyle=UIModalTransitionStyleCrossDissolve时是不隐藏的，故不执行
    [super viewWillDisappear:animated];
    if (_headerADView.totalNum>1) {
        [_headerADView closeTimer];//关闭定时器
    }
}
#pragma mark - scrollView也是适用于tableView的cell滚动 将开始和将要结束滚动时调用
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [_headerADView closeTimer];//关闭定时器
}
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    if (_headerADView.totalNum>1) {
        [_headerADView openTimer];//开启定时器
    }
}


#pragma mark -CollectionView datasource
//section
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
//item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return arr.count;
    
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //重用cell
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kcellIdentifier forIndexPath:indexPath];
    VideoModel*vmodel=[arr objectAtIndex:indexPath.row];
    //赋值
    UIImageView *imageView = (UIImageView *)[cell viewWithTag:1];
    UILabel *toplabel = (UILabel *)[cell viewWithTag:2];
    toplabel.text=vmodel.category_NAME;
    UILabel *bottomlabel = (UILabel *)[cell viewWithTag:3];
    bottomlabel.text=vmodel.video_NAME;

    [imageView setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:vmodel.video_SNAPSHOT_URL]] placeholderImage:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
        imageView.image=image;
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
    }];
    
    cell.backgroundColor = [UIColor whiteColor];
    return cell;
    
}
// The view that is returned must be retrieved from a call to -dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath:
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    UICollectionReusableView *view =nil;
    if (kind==UICollectionElementKindSectionHeader) {
        view =[collectionView dequeueReusableSupplementaryViewOfKind :kind   withReuseIdentifier:kheaderIdentifier   forIndexPath:indexPath];
        
        _headview.frame=CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width,395);
        
        [view addSubview: _headview];
    }
    if (kind==UICollectionElementKindSectionFooter) {
        view=[collectionView dequeueReusableSupplementaryViewOfKind :kind   withReuseIdentifier:kfooterIdentifier   forIndexPath:indexPath];
        _footView.frame=CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.width/375*139);
        [view addSubview: _footView];
    }

    return view;
}
//定义每个UICollectionViewCell 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((fDeviceWidth-20)/2, (fDeviceWidth-20)/2+50);
}
//定义每个Section 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 5, 10, 5);//分别为上、左、下、右
}
//返回头headerView的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    CGSize size={_headview.frame.size.width,_headview.frame.size.height};
    return size;
}
////返回头footerView的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    CGSize size={_footView.frame.size.width,_footView.frame.size.height};
    return size;
}
//每个section中不同的行之间的行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}
//每个item之间的间距
//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
//{
//    return 100;
//}
//选择了某个cell
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    VideoModel *vmodel=[arr objectAtIndex:indexPath.row];
    MPMoviePlayerViewController *playerViewController =[[MPMoviePlayerViewController alloc]initWithContentURL:[NSURL URLWithString:[vmodel.video_URL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
    [self presentMoviePlayerViewControllerAnimated:playerViewController];
    
}
//取消选择了某个cell
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    [cell setBackgroundColor:[UIColor redColor]];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)selectCityAction:(id)sender {
}

- (IBAction)msgAction:(id)sender {

}
- (IBAction)teacherPWAction:(id)sender {
    JiaoShiPaiMingViewController *vc=[[JiaoShiPaiMingViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)woyaoyuekeAction:(id)sender {
    YueKeViewController *vc=[[YueKeViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)lianxiliebiaoAction:(id)sender {
    ChatListViewController *vc = [[ChatListViewController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark - private
//登陆状态改变
-(void)loginStateChange:(NSNotification *)notification
{
    
//    BOOL isAutoLogin = [[[EaseMob sharedInstance] chatManager] isAutoLoginEnabled];
//    BOOL loginSuccess = [notification.object boolValue];
//    
//    if (isAutoLogin || loginSuccess) {//登陆成功加载主窗口控制器
        //加载申请通知的数据
//        [[ApplyViewController shareController] loadDataSourceFromLocalDB];
//        
//        MainViewController *mainChatVC = [[MainViewController alloc] init];
//        [mainChatVC networkChanged:eEMConnectionConnected];
//        [self.navigationController pushViewController:mainChatVC animated:YES];
        
        // 环信UIdemo中有用到Parse，您的项目中不需要添加，可忽略此处。
        //        [self initParse];
//    }else{//登陆失败加载登陆页面控制器
//        
//        UIStoryboard *stdb = [UIStoryboard storyboardWithName:@"LoginRegister" bundle:[NSBundle mainBundle]];
//        UIViewController *loginVC = [stdb instantiateViewControllerWithIdentifier:@"LoginViewController"];
//        [self.navigationController pushViewController:loginVC animated:YES];
//        
//    }
}

- (IBAction)myComentAction:(id)sender {
}
- (IBAction)hotConmentAction:(id)sender {
}

- (IBAction)zhoubianTeacherAction:(id)sender {
    
    AroudTeachersViewController *vc=[[AroudTeachersViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)youxiuTeacherAction:(id)sender {
    GoodTeacherViewController *vc=[[GoodTeacherViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (IBAction)getinhuodongAction:(id)sender {
    HuoDongViewController *vc=[[HuoDongViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)gengduotuijianAction:(id)sender {
//    UIStoryboard *sb=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
//    UIViewController* test2obj = [sb instantiateViewControllerWithIdentifier:@"tabbarID"];
//    [self.navigationController presentViewController:test2obj animated:YES completion:^{
//    }];
    
    TuijianShipinViewController *vc=[[TuijianShipinViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}
@end
